//存储选择的数据
var checkedNodes = [];
layui.use(['element', 'form', 'layer', 'upload', 'jquery'], function () {
    var element = layui.element;
    var form = layui.form;
    var layer = layui.layer;
    var upload = layui.upload;
    var $ = layui.jquery;
    //使用着id
    var createId = localStorage.getItem('createId');
    $('input[name=userId]').val(createId);
    $('input[name=createId]').val(createId);
    //弹出框课程类型
    var index;
    //分类id
    var categroyId;
    //分类名称
    var title;
    //分类内容
    var classifyContent;
    popup = function popup() {
        index = layer.open({
            type: 1,
            title: '课程分类',
            offset: 'auto',
            maxmin: true,
            shade: 0,
            area: ['500px', '400px'],
            content: '<ul id="ztree" class="ztree"></ul>',
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                $('input[name=classId]').val(categroyId);
                $('input[name=title]').val(title);
                $('#type').text(classifyContent);
                $('#courseSort').show();
                layer.close(index);
            }
        });
        //树的配置
        var setting = {
            view:{
              showIcon:true,
              selectedMulti:false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: 'categroyId',
                    pIdKey: 'parentId',
                    rootPId: -1
                },
                key: {
                    name: 'title'
                }
            },
            check: {
                enable: true,
                chkStyle: 'checkbox',
                chkboxType: {
                    'Y': 'ps',
                    'N': 's'
                },
                nocheckInherit: true
            },
            callback: {
                onCheck: onCheck,//选择复选框
                onClick: chooseNode//点击节点
            }

        }

        //加载树的数据
        $.ajax({
            url: "/courseClass/getCourseClass",
            type: "post",
            dataType: 'json',
            success: function (data) {
                var zTree = $.fn.zTree.init($("#ztree"), setting, data.data); //加载数据
                zTree.expandAll(true);//展开节点
                //回显数据
                var treeObj = $.fn.zTree.getZTreeObj('ztree');
                for (var i = 0;i<checkedNodes.length;i++){
                    var nodeByParam = treeObj.getNodeByParam('categroyId', checkedNodes[i]);
                    treeObj.checkNode(nodeByParam,true);
                }
            }
        });

        //点击节点
        function chooseNode(event, treeId, treeNode) {
            if (treeNode.title == '选择分类类型') {
                layer.msg("请选择分类类型");
                return;
            } else {
                $('#type').text(treeNode.title);
                $('input[name=classId]').val(treeNode.categroyId);
                $('input[name=title]').val(treeNode.title);
                checkedNodes += treeNode.categroyId;
                //显示选择分类
                $('#courseSort').show();
                //关闭弹出层
                layer.close(index);
            }
        }


        //选择复选框
        function onCheck(event, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj("ztree"),
                nodes = treeObj.getCheckedNodes(true),
                type = "";
            checkedNodes = [];
            for (var i = 1; i < nodes.length; i++) {
                checkedNodes += nodes[i].categroyId;
                type += nodes[i].title + ">";
                categroyId = nodes[i].categroyId;
                title = nodes[i].title;
            }
            classifyContent = type.substring(0, type.lastIndexOf('>'));
        }
    }
    //上传图片
    var uploadInst = upload.render({
        elem: '#test',
        url: '/upload/uploadFile',
        field: 'files',
        accept: 'images',
        auto: true,
        multiple: true,
        acceptMime: 'image/*',
        number: 6,
        before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#imgs').prepend('<li class=\'layui-left layui-li\'>' +
                    '<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">' +
                    '<i class=\'del\'>x</i>' +
                    '</li>');
            });
        },
        done: function (res) {
            //上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            $('input[name=url]').val(res.data.path);
        }
    });
    //删除照片
    $(document).on("click", ".layui-li .del", function(event){
        $(this).parent().remove();
    })
    //上传视频
    upload.render({
        elem: '#video',
        url: '/upload/uploadFile',
        field: 'files',
        accept: 'video',
        exts: 'avi|rmvb|rm|wmv|mpg|mpeg|mov|ram|swf|flv|mp4|ogv',
        before: function (obj) {
            //展示视频预览
            $('#videoPreview').show();
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#courseUrl').attr('src', result);
                $('#courseUrl').attr('alt', file.name);
                //计算时长
                var minutes;
                var i = setInterval(function () {
                    var time = document.querySelector("#courseUrl");
                    var readyState = time.readyState;
                    if (readyState > 0) {
                        if (time.duration < 60) {
                            minutes = 1;
                        }else {
                            minutes = Math.ceil(time.duration/60);
                        }
                        $('input[name=courseTime]').val(minutes);
                        clearInterval(i);
                    }
                }, 200);

            });
            element.progress('demo', '0%'); //进度条复位
            layer.msg('上传中', {icon: 16, time: 0});
        },
        done: function (res) {
            layer.msg('上传成功');
            $('input[name=courseUrl]').val(res.data.path);
        },
        //进度条
        progress: function (n, elem, e) {
            element.progress('demo', n + '%');
            if (n == 100) {
                layer.msg('上传完毕', {icon: 1});
            }
        }
    });
    //完成
    form.on('submit(sub)', function (data) {
        //添加课程列表
        $.ajax({
            url: '/course/addCourse',
            type: 'post',
            dataType: 'json',
            data: data.field,
            success: function (data) {
                if (data.data != null) {
                    //添加到审核列表
                    var record = {
                        'courseId': data.data.courseId,
                        'launchId': createId,
                        'result': '2',
                        'type': 2
                    }
                    $.ajax({
                        url: '/record/addRecord',
                        type: 'post',
                        dataType: 'json',
                        data: record,
                        success: function (data) {
                            if (data.data) {
                                layer.msg('提交成功');
                                //跳转课程列表
                                parent.$('#Jump').val('课程列表');
                                parent.getQuick();
                                parent.getTable();
                                return;
                            }
                        }
                    });
                }
            }
        });
        return false;
    })
    //校验价格
    form.verify({
        price: function (value, item) {
            if (/^-[0-9]*[1-9][0-9]*$/.test(value)) {
                return '价格不能为负数';
            }
        }
    });
    //刷新
    $('#refresh').on('click', function () {
        location.reload();
    })
    //返回
    $('#goBack').on('click', function () {
        //跳转课程列表
        parent.$('#Jump').val('课程列表');
        parent.getQuick();
        return;
    })
})